import { Component, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs';

import { DestroyService, FileService } from '@core/base';
import { Metadata, LocalService } from '@core/oss/local';

@Component({
  selector: 'app-local-view',
  templateUrl: './local-view.component.html',
  providers: [DestroyService]
})
export class LocalViewComponent implements OnInit {
  ids: string = '';
  metadataList: Metadata[] = [];
  isLoading = false;

  constructor(private filesSrc: FileService, private localSrc: LocalService, private destroy: DestroyService) {}

  ngOnInit(): void {
    this.localSrc.onUpload.pipe(takeUntil(this.destroy)).subscribe(metadata => {
      if (metadata.id) {
        const idArray = this.ids.split(',');
        idArray.push(metadata.id);
        this.ids = idArray.filter(e => e !== undefined && e !== null && e.trim().length > 0).join(',');
      }
    });
    this.localSrc.onRemove.pipe(takeUntil(this.destroy)).subscribe(metadata => {
      const idArray = this.ids.split(',').filter(e => e !== metadata.id);
      this.ids = idArray.join(',');
    });
  }

  downloadAll(): void {
    const metadataIds: string[] = [];
    this.metadataList
      .map(e => e.id)
      .forEach(e => {
        if (e !== undefined) {
          metadataIds.push(e);
        }
      });
    if (metadataIds.length === 0) {
      return;
    }

    this.isLoading = true;
    this.localSrc.downloads(metadataIds).subscribe(data => {
      this.filesSrc.saveAsFile(data, '');
      this.isLoading = false;
    });
  }

  find(): void {
    const metadataIds = this.ids.split(',');
    if (metadataIds.length === 0) {
      return;
    }

    this.isLoading = true;
    this.localSrc.getMetadataByIds(metadataIds).subscribe(data => {
      this.metadataList = [...data];
      this.isLoading = false;
    });
  }
}
